using MediatR;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using RabbitTraceability.Api.Applications.Command;
using RabbitTraceability.Api.Dtos.Response;
using ErrorCode;
using System;
using System.Threading.Tasks;

namespace RabbitTraceability.Api.Controllers
{
    /// <summary>
    /// 保健信息控制器
    /// </summary>
    [ApiController]
    [Route("api/[controller]/[action]")]
    public class HealthCareController : ControllerBase
    {
        private readonly IMediator _mediator;
        private readonly ILogger<HealthCareController> _logger;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="mediator">中介者</param>
        /// <param name="logger">日志记录器</param>
        public HealthCareController(IMediator mediator, ILogger<HealthCareController> logger)
        {
            _mediator = mediator;
            _logger = logger;
        }

        /// <summary>
        /// 添加保健信息
        /// </summary>
        /// <param name="request">添加保健信息请求</param>
        /// <returns>操作结果</returns>
        [HttpPost]
        [Authorize]
        public async Task<IActionResult> AddHealthCareInfo([FromBody] AddHealthCareInfoCommand request)
        {
            try
            {
                _logger.LogInformation("收到添加保健信息请求，批次：{ProductionBatch}", request.ProductionBatch);

                // 发送命令
                var healthCareId = await _mediator.Send(request);

                _logger.LogInformation("成功添加保健信息，保健编号：{HealthCareId}", healthCareId);

                return Ok(ApiResult<string>.SuccessWithData(healthCareId, "保健信息添加成功"));
            }
            catch (ApiException ex)
            {
                _logger.LogWarning("添加保健信息业务异常：{Message}", ex.Message);
                return BadRequest(ApiResult<object>.Error(ex.Code, ex.Message));
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "添加保健信息时发生未处理异常");
                return StatusCode(500, ApiResult<object>.Error(ResultCode.InternalServerError, "服务器内部错误"));
            }
        }

        /// <summary>
        /// 根据生产批次查询保健信息
        /// </summary>
        /// <param name="productionBatch">生产批次</param>
        /// <returns>保健信息</returns>
        [HttpGet]
        [Authorize]
        public async Task<IActionResult> GetHealthCareInfoByBatch([FromQuery] string productionBatch)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(productionBatch))
                {
                    _logger.LogWarning("查询保健信息时生产批次参数为空");
                    return BadRequest(ApiResult<object>.BadRequest("生产批次不能为空"));
                }

                _logger.LogInformation("收到查询保健信息请求，生产批次：{ProductionBatch}", productionBatch);

                // 创建查询命令
                var queryCommand = new QueryHealthCareInfoCommand(productionBatch);

                // 发送查询命令，现在返回的是ApiResult格式
                var result = await _mediator.Send(queryCommand);

                // 直接返回结果，因为处理器已经返回了ApiResult格式
                if (result.Success)
                {
                    _logger.LogInformation("成功查询保健信息，保健编号：{HealthCareId}", result.Data?.HealthCareId);
                    return Ok(result);
                }
                else
                {
                    _logger.LogWarning("查询保健信息失败：{Message}", result.Message);
                    return BadRequest(result);
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "查询保健信息时发生未处理异常");
                return StatusCode(500, ApiResult<object>.ServerError("服务器内部错误"));
            }
        }

        /// <summary>
        /// 修改保健信息
        /// </summary>
        /// <param name="request">修改保健信息请求</param>
        /// <returns>操作结果</returns>
        [HttpPut]
        [Authorize]
        public async Task<IActionResult> UpdateHealthCareInfo([FromBody] UpdateHealthCareInfoCommand request)
        {
            try
            {
                _logger.LogInformation("收到修改保健信息请求，保健编号：{HealthCareId}，批次：{ProductionBatch}", 
                    request.HealthCareId, request.ProductionBatch);

                // 发送修改命令
                var result = await _mediator.Send(request);

                _logger.LogInformation("成功修改保健信息，保健编号：{HealthCareId}", request.HealthCareId);

                return Ok(ApiResult<bool>.SuccessWithData(result, "保健信息修改成功"));
            }
            catch (ApiException ex)
            {
                _logger.LogWarning("修改保健信息业务异常：{Message}", ex.Message);
                return BadRequest(ApiResult<object>.Error(ex.Code, ex.Message));
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "修改保健信息时发生未处理异常");
                return StatusCode(500, ApiResult<object>.Error(ResultCode.InternalServerError, "服务器内部错误"));
            }
        }

        /// <summary>
        /// 删除保健信息
        /// </summary>
        /// <param name="healthCareId">保健编号</param>
        /// <returns>操作结果</returns>
        [HttpDelete]
        [Authorize]
        public async Task<IActionResult> DeleteHealthCareInfo([FromQuery] string healthCareId)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(healthCareId))
                {
                    _logger.LogWarning("删除保健信息时保健编号参数为空");
                    return BadRequest(ApiResult<object>.BadRequest("保健编号不能为空"));
                }

                _logger.LogInformation("收到删除保健信息请求，保健编号：{HealthCareId}", healthCareId);

                // 创建删除命令
                var deleteCommand = new DeleteHealthCareInfoCommand(healthCareId);

                // 发送删除命令
                var result = await _mediator.Send(deleteCommand);

                _logger.LogInformation("成功删除保健信息，保健编号：{HealthCareId}", healthCareId);

                return Ok(ApiResult<bool>.SuccessWithData(result, "保健信息删除成功"));
            }
            catch (ApiException ex)
            {
                _logger.LogWarning("删除保健信息业务异常：{Message}", ex.Message);
                return BadRequest(ApiResult<object>.Error(ex.Code, ex.Message));
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "删除保健信息时发生未处理异常");
                return StatusCode(500, ApiResult<object>.Error(ResultCode.InternalServerError, "服务器内部错误"));
            }
        }
    }
} 